package cn.zjitc.web.servlet;

import cn.zjitc.domian.Product;
import cn.zjitc.service.ProductService;
import cn.zjitc.service.impl.ProductServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author dell
 * @date 2020/7/3 8:54
 */
@WebServlet("/addProductServlet")
public class AddProductServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> par = request.getParameterMap();
        Product product = new Product();
        try {
            BeanUtils.populate(product,par);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        ProductService productService =new ProductServiceImpl();
        Product product1 = productService.fingProductByName(product.getName());
        if(product1==null){
            productService.addProduct(product);
            response.sendRedirect(request.getContextPath()+"/findAllServlet");
        }else{
            request.setAttribute("msg","名称不能重复");
            request.getRequestDispatcher("/add.jsp").forward(request,response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
